import React, {Component} from 'react';
import GridTable from '../../components/display/gridTable';
import { Button, Select, Tooltip, Row, Col, Divider, message, Modal } from 'antd';
import ScModal from '../../components/feedback/scModal';
import { voucherList, getOrderDetail } from '../../fetch/fetchApi';
import PropsType from "prop-types";
import VoucherUseDetail from "./useDetail";
const Option = Select.Option;

class Voucher extends Component {
  constructor (props) {
    super(props);
    this.props = props;
    this.state = {
      gridData: null,
      loadingmes: '查询',
      loading: !1,
      btnloading: !1,
      pagination: {
        total: 0
      }
    };
    this.init();
    window.LayoutTab && setTimeout(() => {
      this.queryChargeInfo();
    }, 1);  }

  init () {
    this.query = {
      page: '1',
      pagecount: '10'
    };
    window.LayoutTab && (this.query['userId'] = window.LayoutTab.tabParam.userId);
    this.params = {};
    this.statusType = {
      '0': '删除',
      '1': '未使用完',
      '2': '已使用',
      '3': '禁用',
      '4': '使用中'
    };
    this.rangeType = {
      '0': '自营桩群',
      '1': '全网桩群',
      '2': '私桩',
      '3': '指定桩群'
    }
    // 设置表头
    this.tableColumns = [
      {
        title: '抵用券编码',
        dataIndex: 'key',
        key: 'key',
        className: 'column-nowrap',
        fixed: 'left',
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        className: 'column-nowrap',
        render: (text, record) => (
          <div>
            {this.statusType[text]}
          </div>)
      }, {
        title: '金额 (元)',
        dataIndex: 'amount',
        key: 'amount',
        className: 'column-nowrap',
      }, {
        title: '余额 (元)',
        dataIndex: 'remainingAmount',
        key: 'remainingAmount',
			className: 'column-nowrap',
      }, {
        title: '适用电站',
        dataIndex: 'rangeType',
        key: 'rangeType',
			className: 'column-nowrap',
      }, {
        title: '券类型',
        dataIndex: 'voucherType',
        key: 'voucherType',
			className: 'column-nowrap',
        render: (text, record) => (
          <div>{text === 0 ? '充电抵用券' : '服务费抵用券'}</div>
        )
      }
      , {
        title: '发券方',
        dataIndex: 'logoName',
        key: 'logoName',
			className: 'column-nowrap',
        render: (text, record) => (<div>{text}</div>)
      }, {
        title: '生成时间',
        dataIndex: 'createTime',
        key: 'createTime',
			className: 'column-nowrap',
      }, {
        title: '有效期',
        dataIndex: 'startTimeStr',
        key: 'startTimeStr',
        className: 'column-nowrap',
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
      }, {
        title: '描述',
        dataIndex: 'info',
        key: 'info',
        className: 'column-nowrap',
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
      }, {
        title: '操作',
        key: 'action',
        fixed: 'right',
			className: 'column-nowrap',
        render: (text, record) => (
          <div className="action-wrap">
            {record.stubGroupId && <span>
            <a href="javascript:void(0);"
               onClick={() => this.openTab({'keyId': record.stubGroupId, 'stubGroupIds': record.stubGroupId}, {'key': 'pslist', titleText: '电站查询'})}>
              查看电站
            </a><Divider type="vertical" /></span>}
            <a href="javascript:void(0);" onClick={()=>this.showDetailModal(record.key)}>使用明细</a>
          </div>
        )
      }
    ];
    this.currentYear = new Date().getFullYear();
    this.selectArrDom = [];
    for (let optionYear = 2015, end = this.currentYear; optionYear <= end; optionYear++) {
      this.selectArrDom.push(<Option key={optionYear} value={optionYear}>{optionYear}</Option>);
    }
    this.query['year'] = this.currentYear;
  }

  showDetailModal=(id)=>{
    this.setState({
      detailModalVisible:true,
      voucherId:id
    })
  }

  // fetch DataSource
  async voucherList () {
    this.setState({
      loading: !0,
      btnloading: !0
    });
    try {
      const resData = await voucherList(this.query);
      let resObj = resData.data.data;
      this.state.pagination.total = resData.data.pageLimit.totalCount;
      if (resData.data.code === '200') {
        for (let r of resObj) {
          r['startTimeStr'] = r['startTimeStr'] + ' - ' + r['endTimeStr'];
        }
        const pagination = {
          total: resData.data.pageLimit.totalCount,
          onShowSizeChange: (current) => {
            this.turnPage(current)
          },
          onChange:(current) => {
            this.turnPage(current)
          }
        }
        this.setState({
          pagination
        });
        return resObj;
      }
    } catch (e) {
      console.log(e);
    }
  }

  // 提交查询
  queryChargeInfo () {
    this.query.page = '1';
    this.state.pagination.current = 1;
    this.setState({
      pagination: this.state.pagination
    });
    this.voucherListCb();
  }

  voucherListCb() {
    this.voucherList().then((data) => {
      this.setState({
        loading: !1,
        btnloading: !1,
        gridData: data,
        pagination: this.state.pagination
      });
    });
  }

  // 跳转页码
  turnPage (current) {
    this.query['page'] = current.toString();
    this.voucherListCb();
  }

  // 注入状态参数
  statusInputHandler (type) {
    this.query['status'] = type;
  }

  // 选择年份
  yearInputHandler (y) {
    this.query['year'] = y;
  }

  // 显示充电过程
  showProgressDetail (id, title) {
    this.setState({
      width: 820,
      modalVisible: !0,
      modalTitle: title
    });
  }

  // fetch 订单详情
  async getOrderDetail (id) {
    try {
      const resData = await getOrderDetail({
        orderId: id
      });
      console.log(resData);
    } catch (e) {
      console.log(e);
    }
  }

  // 取消弹窗
  cancel () {
    this.setState({
      modalVisible: !1,
      confirmLoading: !1
    });
  }

  // 打开tab
  openTab (id, e) {
    this.props.onAdd.bind(window.LayoutTab)(e, id);
  }

  handleDetailModalCancel=()=>{
    this.setState({
      detailModalVisible:false
    })
  }

  render () {
    const Content = <div className="sc-page-content">
      <div className="page-toolbar">
        <Row gutter={8}>
          <Col lg={8} xl={6}>
            <Select onChange={this.yearInputHandler.bind(this)} defaultValue={this.currentYear} className="modal-select" placeholder="选择年份">
              {this.selectArrDom}
            </Select>
          </Col>
          <Col lg={8} xl={6}>
            <Select onChange={this.statusInputHandler.bind(this)} className="modal-select" placeholder="选择状态">
              <Option value={'1'}>未使用完</Option>
              <Option value={'2'}>已使用</Option>
              <Option value={'3'}>禁用</Option>
              <Option value={'4'}>使用中</Option>
            </Select>
          </Col>
          <div className={'button-inlineBlock'}>
            <Button type="primary" onClick={this.queryChargeInfo.bind(this)}>{this.state.loadingmes}</Button>
          </div>
        </Row>
      </div>
      <div className="page-panel">
        <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
        <ScModal
          width={this.state.width}
          modalVisible={this.state.modalVisible}
          modalTitle={this.state.modalTitle}
          modalContent={this.state.modalContent}
          footer={null}
          cancel={this.cancel.bind(this)}
        />
      </div>
      <Modal width="800px" visible={this.state.detailModalVisible} footer={null} onCancel={this.handleDetailModalCancel}>
        <VoucherUseDetail id={this.state.voucherId}/>
      </Modal>
    </div>;

    return Content;
  }
}

export default Voucher;

Voucher.propTypes = {
  onAdd: PropsType.func
}